package db;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import boot.Boot;

public class SimpleDBReader {

	private String dbFile;
	private SimpleDBListener[] listeners;
	private int numListeners = 0;

	private FileConnection fc;
	private InputStream fis;
	private String currentString;
	private boolean fileDone;
	private boolean dataDone; // on RAM as opposed to "on file"
	private boolean readInterrupted;

	public SimpleDBReader(String aDBFIle) {
		dbFile = aDBFIle;
		listeners = new SimpleDBListener[20];
		readInterrupted = false;
		fileDone = false;
		dataDone = false;
		currentString = null;
	}

	public void readDB() {
		try {

			setupInputStream();
			currentString = readFromFile();
			while ((!dataDone) && (!readInterrupted)) {
				String line = getNextLine();
				callListeners(line);
			}
			endListeners();

		} catch (IOException e) {
			Boot.alertException(e, this, "readDB()");
		}
	}

	private void endListeners() {
		for (int i = 0; i < numListeners; i++) {
			listeners[i].readingDone();
		}
	}

	private void callListeners(String line) {
		for (int i = 0; i < numListeners; i++) {
			listeners[i].processLine(line);
		}
	}

	public void addListener(SimpleDBListener listener) {
		listeners[numListeners++] = listener;
	}

	private String getNextLine() throws IOException {
		String result = null;

		if ((!fileDone) && (currentString.length() < 100)) {
			String next = readFromFile();
			if (next != null) {				
				currentString += next;
			}
		}

		int returnIndex = currentString.indexOf("\r\n");
		if (returnIndex < 0) {
			result = currentString;
			dataDone = true;
		} else {
			result = currentString.substring(0, returnIndex);
			currentString = currentString.substring(returnIndex + 2,
					currentString.length());
			if (currentString.length() == 0) {
				dataDone = true;
			}
		}
		return result;
	}

	private void setupInputStream() throws IOException {
		fc = (FileConnection) Connector.open(dbFile);

		if ((fc == null) || (!fc.exists())) {
			throw new IOException("File \"" + dbFile + "\" does not exists");
		}
		fis = fc.openInputStream();
	}

	private String readFromFile() throws IOException {
		String result = null;
		int bufferLength = 512;
		byte[] b = new byte[bufferLength];
		int length = fis.read(b, 0, bufferLength);

		if (length > 0) {
			result = new String(b, 0, length);
			// result = new String(b, 0, length, "ISO-8859-1");
		} else {
			fileDone = true;
			closeStreams();
		}
		return result;
	}

	private void closeStreams() throws IOException {
		fis.close();
		fc.close();
		fis = null;
		fc = null;
	}

	public void stopReading() throws IOException {
		readInterrupted = true;
		closeStreams();
	}
}
